<!--
 * @Author: windys
 * @Description: 
 * @Date: 2022-02-15 14:28:59
-->
<template>
  <div class="chat_page" id="chat_page">
    <div class="chat_list">
      <div class="chat_msg_item" v-for="(item, index) in mgsList" :key="index">
        <!-- 文字消息 -->
        <div v-if="item.type === 'text'" class="text_container">
          <p class="content">
            <span style="color: red"
              >{{ item.fromNick }}
              <i v-if="item.custom">
                ( {{ JSON.parse(item.custom).level
                }}{{ JSON.parse(item.custom).status }})</i
              >
              ：</span
            >{{ item.text }}
          </p>
        </div>

        <!-- 系统通知 -->
        <div v-if="item.type === 'notification'" class="text_container">
          <p class="content" v-if="item.attach.type === 'memberEnter'">
            <span style="color: #ff9900"
              >{{ item.attach.toNick[0] }}进入直播间</span
            >
          </p>
          <p class="content" v-if="item.attach.type === 'gagMember'">
            <span style="color: #ff9900"
              >{{ item.attach.toNick[0] }}被禁言</span
            >
          </p>
          <p class="content" v-if="item.attach.type === 'ungagMember'">
            <span style="color: #ff9900"
              >{{ item.attach.toNick[0] }}解除禁言</span
            >
          </p>
        </div>

        <!-- 礼物消息 -->
        <div v-if="item.type === 'custom'" class="text_container">
          <p class="content" v-if="JSON.parse(item.content).type === 8">
            <span style="color: red"
              >{{ item.fromNick }}送出礼物：<img
                :src="JSON.parse(item.content).data.gift_img"
                style="
                  width: 35px;
                  height: 35px;
                  position: relative;
                  top: 10px;
                "
            /></span>
          </p>
        </div>
      </div>
      <div class="position-box"></div>
    </div>

    <!-- 礼物 -->
    <giftDialog ref="giftDialog" @handleSendGift="handleSendGift"></giftDialog>
    <!-- 发言 -->
    <liveSay
      @handleSend="handleSend"
      @handleSendGift="handleSendGiftOpen"
    ></liveSay>
    <!-- 带货商品 -->
    <goodsDialog @handleLiveGoodsBuySucc="handleLiveGoodsBuySucc"></goodsDialog>
  </div>
</template>




<script >
import { computed, defineComponent, onMounted, ref } from "vue";
import { getLiveRoomAdress, sendGift } from "@/api/live";
import { useRoute, useRouter } from "vue-router";
import storage from "@/utils/storage";
import parseStringJson from "@/utils/parse";
import liveSay from "./liveSay.vue";
import { useStore } from "@/store";
import { Dialog, Notify, Toast } from "vant";
import giftDialog from "./giftDialog.vue";
import goodsDialog from "./goodsDialog.vue";
export default defineComponent({
  components: {
    liveSay,
    giftDialog,
    goodsDialog,
  },
  setup(props, { emit }) {
    const router = useRouter();
    const route = useRoute();

    const store = useStore();

    onMounted(() => {
      initRoom();
    });

    const onChatroomConnect = (obj) => {
      console.log(obj, "聊天室已链接");
    };
    const onChatroomError = (error, obj) => {
      console.log(error, "聊天室链接错误");
    };
    const onChatroomWillReconnect = (obj) => {
      console.log("即将重连");
    };
    const onChatroomDisconnect = (obj) => {
      console.log("断开链接", obj);
      if (obj.code === "kicked") {
        Notify({ type: "danger", message: "您已被踢出直播间" });
        router.push("/live");
      }
    };
    const onChatroomMsgs = (msgs) => {
      console.log("收到聊天室消息", msgs);
      if (document.getElementById("chat_page")) {
        document.getElementById("chat_page").scrollTop =
          document.getElementById("chat_page").scrollHeight + 200; //滚动最底部
      }
      // 普通消息
      if (msgs[0].type == "text") {
        store.addMsgList(msgs);
        emit("sendDanMu", msgs);
      }

      // 系统消息
      if (msgs[0].type == "notification") {
        store.addMsgList(msgs);
      }

      // 礼物消息 自定义
      if (msgs[0].type == "custom") {
        store.addMsgList(msgs);
      }

      // 购买消息
      if (msgs[0].type == "custom" && msgs[0].content) {
        let news = JSON.parse(msgs[0].content);
        if (news.type == 18) {
          Notify({ type: "success", message: news.data.msg });
        }
      }

      // 直播间禁用
      if (msgs[0].type == "custom" && msgs[0].content) {
        let news = JSON.parse(msgs[0].content);
        if (news.type == 14) {
          Dialog.confirm({
            title: "提示",
            message: "主播涉嫌违规，暂停直播。请解封后正常观看",
          })
            .then(() => {
              // on confirm
              router.push("/live");
            })
            .catch(() => {
              // on cancel
              router.push("/live");
            });
        }
      }
    };

    const initRoom = async () => {
      const res = await getLiveRoomAdress({
        chatRoomId: route.query.chatRoomId,
      });
      if (res) {
        window.chatroom = window.SDK.Chatroom.getInstance({
          isAnonymous: storage.getStorage("v3_userinfo_mobile") ? false : true,
          chatroomNick: storage.getStorage("v3_userinfo_mobile")
            ? JSON.parse(storage.getStorage("v3_userinfo_mobile")).nick
            : `游客${Math.random().toFixed(6).slice(-6)}`,
          appKey: "6ad8de7a2cbd06ec21938746ff8fc884",
          account: storage.getStorage("v3_userinfo_mobile")
            ? JSON.parse(storage.getStorage("v3_userinfo_mobile")).userId
            : "",
          token: storage.getStorage("v3_userinfo_mobile")
            ? JSON.parse(storage.getStorage("v3_userinfo_mobile")).imToken
            : "",
          chatroomId: route.query.chatRoomId,
          chatroomAvatar: storage.getStorage("v3_userinfo_mobile")
            ? JSON.parse(storage.getStorage("v3_userinfo_mobile")).headUrl
            : "../../assets/img/defaultlogo.png",
          chatroomAddresses: res, //地址
          onconnect: onChatroomConnect,
          onerror: onChatroomError,
          onwillreconnect: onChatroomWillReconnect,
          ondisconnect: onChatroomDisconnect,
          // 消息
          onmsgs: onChatroomMsgs,
        });

        // 成员
        setTimeout(() => {
          handleGetRoomMember();
        }, 1000);
      }
    };

    const members = ref([]);
    const handleGetRoomMember = () => {
      window.chatroom.getChatroomMembers({
        guest: true,
        // time: time,
        limit: 200,
        done: getChatroomMembersDone,
      });
      function getChatroomMembersDone(error, obj) {
        if (obj && obj.members && obj.members.length) {
          members.value = obj.members;
          emit("handleGetRoomMember", members.value);
        } else {
          console.log("获取成员----------------", error);
          Toast.fail(error);
        }
      }
    };

    //发送文字消息
    const userSelft = storage.getStorage("v3_userinfo_mobile")
      ? JSON.parse(storage.getStorage("v3_userinfo_mobile"))
      : null;
    const handleSend = (text) => {
      window.chatroom.sendText({
        text: text,
        custom: {
          // type: _this.roomRole,
          level: userSelft ? userSelft.levelSubName : "LV1",
          status: userSelft ? userSelft.levelName : "大众用户",
        },
        done: function sendChatroomMsgDone(error, msg) {
          if (!error) {
            store.addMsgList(msg);
          } else {
            Toast.fail(error.message);
          }
        },
      });
    };

    const giftDialog = ref();
    const handleSendGiftOpen = () => {
      giftDialog.value.show = true;
    };

    const handleSendGift = async (item) => {
      const res = await sendGift({
        giftId: item.giftId,
        purchaseNum: 1,
        liveId: route.query.liveId,
      });
      if (typeof res === "string") {
        window.chatroom.sendCustomMsg({
          // 自定义消息体
          content: JSON.stringify({
            type: 8,
            data: {
              count: 1,
              gift_id: item.giftId,
              gift_img: item.imgUrl,
              gift_dynamic: item.dynamicUrl,
            },
          }),
          done: function sendChatroomMsgDone(error, msg) {
            if (!error) {
              store.addMsgList(msg);
            } else {
              Toast.fail(error.message);
            }
          },
        });
      }
      if (res === 1011) {
        store.openRecharge();
      }
    };

    // 发送购买消息
    const handleLiveGoodsBuySucc = (item) => {
      window.chatroom.sendCustomMsg({
        // 自定义消息体
        content: JSON.stringify({
          type: 18,
          data: {
            msg: `${
              JSON.parse(storage.getStorage("v3_userinfo_mobile")).nick
            }购买了${item.data.title}`,
          },
        }),
        done: function sendChatroomMsgDone(error, msg) {
          if (!error) {
            store.addMsgList(msg);
          } else {
            Toast.fail(error.message);
          }
        },
      });
    };

    const handleLeaveRoom = () => {
      // 断开聊天室
       window.chatroom&&window.chatroom.disconnect();
    };
    return {
      store,
      giftDialog,
      members,
      handleSend,
      handleSendGiftOpen,
      handleSendGift,
      handleLeaveRoom,
      handleLiveGoodsBuySucc,
      mgsList: computed(() => store.MGS_LIST),
    };
  },
});
</script>




<style lang="scss" scoped>
.chat_page {
  position: absolute;
  background: #191c26;
  width: 100%;
  bottom: 0;
  top: 300px;
  font-size: 12px;
  overflow-x: hidden;
  overflow-y: auto;
  .chat_list {
    display: flex;
    padding: 5px;
    flex-direction: column;
    padding-bottom: 50px;
    .chat_msg_item {
      color: #fff;
      .text_container {
        text-align: left;
        display: flex;
        .content {
          word-break: break-all;
          word-wrap: break-word;
          i {
            font-size: 10px;
            color: #fdcf00;
          }
        }
      }
    }
  }
}
</style>